const moment = require('moment')
const { manager } = require('../models/index')
const errorHelper = require('../util/errorHelper')
const tokenGenerator = require('../util/tokenGenerator')

class ManagerController {
  constructor() {
    // empty
  }

  async login({ managerId, password }) {
    const isExist = await this.checkExist({ managerId })
    if (!isExist) {
      throw errorHelper(400, 'account or password error')
    }
    if (isExist.password !== password) {
      throw errorHelper(400, 'account or password error')
    }
    const mId = isExist.managerId
    const loginToken = tokenGenerator.generate(managerId, 10)
    const loginTime = moment()
    const outdateTime = moment().add(12, 'h') // token有效期：12小时
    const result = await manager.update({ token: loginToken, loginTime, outdateTime }, { where: { managerId } })
    const managerRes = this.getManagerByKey({ managerId: mId })
    return managerRes
  }

  async addMember({ managerId, password, power }) {
    const result = await manager.create({ managerId, password, power })
    return result
  }
  // async checkToken() {
  // }
  async checkExist(info) {
    const isExist = await manager.findOne({ where: info })
    if (isExist && isExist.managerId) {
      return isExist
    }
    return false
  }
  async checkTokenValid(token) {
    const managerRes = await manager.findOne({
      where: { token, outdateTime: { $gt: moment() } }
    })
    if (!managerRes) {
      throw errorHelper(400, 'token outdate', 1001)
    }
    return managerRes
  }
  async getManagerByKey(where) {
    const managerRes = await manager.findOne({ where })
    if (!managerRes) {
      throw errorHelper(400, 'field error')
    }
    return managerRes
  }
}

module.exports = new ManagerController()
